const express = require('express');
const app = express()
const port = 3000
const cors=require('cors')



const memberRouter = require('./member.router')
const skuRouter = require('./sku.router')

const models = require('../models');//模型对象

// 解决跨域问题
app.use(cors({
    origin: "*",
    credentials:true
}))

/**
 * 增加
 * **/
app.post('/create', async (req, res) => {
    let { name } = req.query;//获取前台的数据，并调用create方法插入前台数据到数据库

    let user = await models.User.create({
        name
    })
    console.log(user);
    res.json({
        message: '创建成功',
        user
    })
    
})

/**
 * 查询
 * **/

// 导出所有表内容
app.get('/list', async (req, res) => {
    let list = await models.User.findAll()
    res.json({
        list
    })
})

// 前端传入id,后端返回相应数据/detail/:id
app.get('/detail/:id', async (req, res) => {
    let { id } = req.params;
  let user=await models.User.findOne({
        where: {
            id
        }
  })
    res.json({
        user,
        message:'查询成功'
    })
})
/**
 * 删除
 * **/
app.get('/delete/:id', async (req, res) => {
    let { id } = req.params;
    await models.User.destroy({
        where: {
          id
        }
    })
    res.json({
        message:'删除成功'
    })
})

// 修改
app.post('/updata', async (req, res) => {
    let { id,name } = req.query;
    await models.User.update({name:name},{
        where: {
          id
        }
    })
    res.json({
        message:'修改成功'
    })
})


app.use('/member',memberRouter)//通过/member/list来进行访问
app.use('/sku',skuRouter)


app.listen(port, () => {
    console.log('服务器启动成功');

})